<template>
  <div>
    <div>
      <el-card class="page-container">
        <el-descriptions class="margin-top" title="个人信息中心" :column="2" border>
          <template slot="extra">
            <el-button class="el-icon-unlock" type="primary" plain @click="addFacePre()">人脸注册</el-button>
            <el-button class="el-icon-edit" circle type="primary" plain
              @click="updateInfo(tableData[0].id)"></el-button>
          </template>

          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user-solid"></i>
              姓名
            </template>
            {{ tableData[0].name }}
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-info"></i>
              编号
            </template>
            {{ tableData[0].id }}
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-phone"></i>
              手机号
            </template>
            {{ tableData[0].phone }}
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-s-grid"></i>
              证件号
            </template>
            {{ tableData[0].idNumber }}
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-s-custom"></i>
              角色类型
            </template>
            <el-tag type="danger"> {{ tableData[0].role }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-s-order"></i>
              密码
            </template>
            {{ tableData[0].password }}
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-s-home"></i>
              归属机构
            </template>
            <el-tag>{{ getAgencyName(tableData[0].agencyId) }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-message-solid"></i>
              账号状态
            </template>
            <el-tag type="success">{{ tableData[0].status }}</el-tag>
          </el-descriptions-item>

        </el-descriptions>


      </el-card>




      <el-dialog :visible.sync="dialogVisible1" title="人脸注册">
        <!-- 拍照功能 -->
        <div>
          <video ref="cameraVideo" autoplay playsinline style="width: 100%; height: auto;"></video>

          <el-button type="primary" plain style="margin-left: 10px" @click="takePhoto">拍照</el-button>

          <canvas ref="cameraCanvas" style="display: none;"></canvas>
          <img :src="photoUrl" alt="拍照图片" v-if="photoUrl" style="width: 100%; height: auto;">
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">关闭</el-button>
        </span>
      </el-dialog>


      <el-dialog :visible.sync="dialogVisible" :before-close="close" title="个人信息编辑" width="25%">
        <el-form :model="user">
          <el-form-item label="姓名" :label-width="formLabelWidth" :rules="[{ required: true }]">
            <el-input v-model="user.name" placeholder="请输入姓名" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" :rules="[{ required: true }]">
            <el-input v-model="user.password" placeholder="请输入密码" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone" :rules="[
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur', required: true }
          ]">
            <el-input v-model="user.phone" placeholder="请输入手机号" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="证件号" :label-width="formLabelWidth" prop="idNumber" :rules="[
            { required: true, pattern: /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/, message: '证件号格式不正确', trigger: 'blur' }
          ]">
            <el-input v-model="user.idNumber" placeholder="请输入证件号" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false; clear()">取消</el-button>
          <el-button type="primary" @click="addForm()">确定</el-button>
        </div>
      </el-dialog>


    </div>

  </div>
</template>
<script>


import { addUser, changeUser, deleteUser, getAllUsers, getInfo } from "@/api/user";
import { getAgencyList } from "@/api/agency";
import { getDocumentVideo } from "@/api/documentVideo";
import { addLearningSituation } from "@/api/learningSituation";
import { addVideoLearningRecords, getVideoLearningRecords } from "@/api/videoLearningRecords";
import { addFace, searchFace } from "@/api/faceRegistration";
import { selectedQuestionAndScore } from "@/api/testPaper";
import { addScore } from "@/api/Score";

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      // cameraVisible: false,
      photoUrl: '',
      cameraStream: null,
      dialogVisible: false,
      dialogVisible1: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      user: { "password": "123456" },
      form: {},
      posts: [],
      multipleSelection: [],
      selectedIds: [],
      agencyList: [],
      formLabelWidth: "80px",
      theMajorOfMy: "",
      //dialogVisible:false,
      data: [
        {
          id: 1,
          label: '视频',
          children: []
        },
        {
          id: 2,
          label: '文档',
          children: []
        },
        {
          id: 3,
          label: '考试',
          children: []
        }
      ],
      xmUser: localStorage.getItem("xm-user") ? JSON.parse(localStorage.getItem("xm-user")) : {},

      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      expandedKeys: [], // 初始时不展开任何节点
      userInFor: {},
      trainingPlanId: 1,
      url: '',
      user_id: 1,
      myInfo: {},
      VideoVisible: false,
      documentVideo: {},
      type: false,
      testVisible: false,
      testQuestionList: [],
      //考试：
      selectedOfOne: '',
      selectedOfMore: [],
      ans: {},//存储所有答案
      selectedAnswers: {},
      click: [],//判断试题是否做
      myScore: '',
      myScoreVisible: false,
    }
  },
  methods: {
    validateAge(rule, value, callback) {
      if (value === undefined || value === null || value === '') {
        return callback(new Error('请输入年龄'));
      }
      if (value < 0 || value > 100) {
        callback(new Error('年龄必须在0到100之间'));
      } else {
        callback();
      }
    },

    show() {
      getInfo().then((res) => {
        let p = []
        if (res.data.code === 1) {
          p.push(res.data.data)
          this.tableData = p;
          console.log(this.tableData)
        }
      }).catch((e) => {
      })
    },
    clear() {
      this.user = {};
      this.show();
    },
    addFacePre() {
      console.log(1111);

      this.initCamera();
      this.dialogVisible1 = true;
      // 取消事件监听，避免重复弹出弹窗
      video.removeEventListener('timeupdate', handleTimeUpdate);
    },
    add() {
      this.user = {};
      this.user.password = "1234567";
      this.addOrUpdate = true;
      this.dialogVisible = true;
    },
    addForm() {

      changeUser(this.user).then(res => {
        console.log(res)
        if (res.data.code === 1) {
          this.$message.success("更新成功")
          this.dialogVisible = false;
          this.user.status = "正常";
          this.show();
        }
      }).catch(e => {
      });


    },

    close() {
      this.dialogVisible = false;
      this.user = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.user = this.tableData.filter(data => data.id == id)[0];
      this.dialogVisible = true;
    },
    getAllAgencyList() {
      getAgencyList().then((res) => {
        if (res.data.code === 1) {
          this.agencyList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getAgencyName(id) {
      let agency = this.agencyList.find(data => data.id === id);
      return agency ? agency.name : "";
    },

    getDocumentVideos() {
      var searchParams = new URLSearchParams(window.location.search);
      var trainPlanId = searchParams.get('trainPlanId');
      this.trainingPlanId = parseInt(trainPlanId, 10);
      getDocumentVideo(this.trainingPlanId, false).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          this.documentVideos = res.data.data;
          this.documentVideos.forEach(resource => {
            // 判断资源类型
            if (resource.url.endsWith('.mp4') || resource.url.endsWith('.mov') || resource.url.endsWith('.avi')) {
              // 视频类型
              this.data[0].children.push({
                id: resource.id,
                label: resource.name,
                url: resource.url
              });
            } else {
              // 其他类型，可以放入考试或其他分类
              this.data[1].children.push({
                id: resource.id,
                label: resource.name,
                url: resource.url
              });
            }
          });
          //跳转版本返回优化
          //this.expandTreeNode(11);
          // 获取当前URL的查询参数
          //var searchParams = new URLSearchParams(window.location.search);
          //var treeNodeId = parseInt(searchParams.get('treeNodeId'), 10);//必须数字，666
          //console.log('treeNodeId',treeNodeId)
          //this.expandTreeNode(treeNodeId);
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    handleNodeClick(data) {
      if (data.id === 3) {
        //试卷
        this.type = false;
        this.VideoVisible = false;
        this.getTestQuestionsListForTest();
        return;
      }

      // 添加自定义文字到查询参数
      console.log(data);
      if (data.url == null) {
        return
      }
      this.documentVideo.id = data.id;
      this.documentVideo.name = data.name;
      this.documentVideo.url = data.url;

      this.VideoVisible = false;
      this.testVisible = false;
      this.myScoreVisible = false;
      this.type = false;

      if (data.url.endsWith('.mp4') || data.url.endsWith('.mov') || data.url.endsWith('.avi')) {
        this.url = data.url;
        //确保数据存在
        this.$nextTick(() => {
          this.VideoVisible = true;
          this.$nextTick(() => {
            this.initVideoPlayer();
          });
        });
      }
      //跳转版本
      /*else if (data.url.endsWith('.pdf')) {
        // 获取当前URL的查询参数
        var searchParams = new URLSearchParams(window.location.search);
        var trainPlanId = searchParams.get('trainPlanId'); // 获取treeNodeId参数
        //浏览pdf
        window.location.href = 'http://localhost:8081/pdfjs-4.9.155-dist/web/viewer.html?file='
            + data.url +"&trainPlanId="+trainPlanId+ "&treeNodeId="+data.id;
      }*/
      //不跳转版本
      else if (data.url.endsWith('.pdf')) {
        //浏览pdf
        this.url = 'http://localhost:8081/pdfjs-4.9.155-dist/web/viewer.html?file=' + data.url;
        this.type = true;
        addLearningSituation(this.trainingPlanId, this.documentVideo.id, 100).then((res) => {
        }).catch((e) => {
        })

      } else {
        addLearningSituation(this.trainingPlanId, this.documentVideo.id, 100).then((res) => {
        }).catch((e) => {
        })
        window.open(data.url, '_blank');
      }

    },
    /*expandTreeNode(treeNodeId) {
      // 设置特定的树节点展开
      this.expandedKeys = [treeNodeId];
    },*/
    initVideoPlayer() {
      const video = this.$refs.myVideo;
      if (video) {
        video.addEventListener('loadedmetadata', () => {
          var searchParams = new URLSearchParams(window.location.search);
          var trainPlanId = searchParams.get('trainPlanId');
          // 设置开始时间
          getVideoLearningRecords(trainPlanId, this.documentVideo.id).then((res) => {
            if (res.data.code === 1) {
              video.currentTime = parseFloat(res.data.data);
            } else {
              console.log("暂无记录或查询失败");
            }
          }).catch((e) => {
            console.error(e);
          });

          // 计算视频一半的时间点
          const halfTime = video.duration / 2;

          // 定义时间更新事件的处理函数
          const handleTimeUpdate = () => {
            // 判断当前播放时间是否接近一半的时间点，这里设置一个容差值，比如5秒
            if (Math.abs(video.currentTime - halfTime) <= 1) {
              // 暂停视频
              video.pause();
              // 显示弹窗
              this.initCamera();
              this.dialogVisible = true;
              // 取消事件监听，避免重复弹出弹窗
              video.removeEventListener('timeupdate', handleTimeUpdate);
            }
          };

          // 监听视频播放时间更新
          video.addEventListener('timeupdate', handleTimeUpdate);
        });

        video.addEventListener('pause', () => {
          console.log(`视频已暂停，当前播放到的时间是：${video.currentTime}秒`);
          // 切换或者播放完毕以及暂停，均会触发
          var searchParams = new URLSearchParams(window.location.search);
          var trainPlanId = searchParams.get('trainPlanId');
          let time = Math.floor(video.currentTime);
          addVideoLearningRecords(trainPlanId, this.documentVideo.id, time).then((res) => {
            if (res.data.code === 1) {
              // console.log("记录成功");
            } else {
              console.log(res.data.msg);
            }
          }).catch((e) => {
            console.error(e);
          });

          let playbackPercentage = Math.floor((video.currentTime / video.duration) * 100);
          // console.log("playbackPercentage", playbackPercentage);
          addLearningSituation(this.trainingPlanId, this.documentVideo.id, playbackPercentage).then((res) => {
          }).catch((e) => {
            console.error(e);
          });
        });
      }
    },
    initCamera() {
      navigator.mediaDevices.getUserMedia({ video: true })
        .then(stream => {
          console.log(this.cameraStream);
          console.log(this.$refs.cameraVideo.srcObject);

          this.cameraStream = stream;
          this.$refs.cameraVideo.srcObject = stream;
        })
        .catch(error => {
          console.error('获取摄像头权限失败', error);
          this.$message.error('获取摄像头权限失败，请确保摄像头可用并重新尝试。');
        });
    },
    closeCamera() {
      if (this.cameraStream) {
        // 关闭摄像头流中的所有轨道
        this.cameraStream.getTracks().forEach(track => {
          track.stop();
        });
        this.cameraStream = null; // 清空摄像头流引用
        this.$refs.cameraVideo.srcObject = null; // 清空视频元素的源对象
      }
    },
    takePhoto() {
      if (this.cameraStream) {
        const canvas = this.$refs.cameraCanvas;
        const video = this.$refs.cameraVideo;
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        const photoData = canvas.toDataURL('image/jpeg');

        // 调试：检查Base64字符串是否正确
        console.log(photoData);

        // 将照片数据发送到服务器
        addFace({ photoData: photoData.split(',')[1], userId: this.myInfo.id }).then(res => {
          if (res.data.code === 1) {
            this.$message.success('照片上传成功');
            // 如果有其他成功后的操作，可以在这里添加
          } else {
            this.$message.error('照片上传失败：' + res.data.msg);
          }
        }).catch(e => {
          this.$message.error('照片上传失败：' + e.message);
        });

        this.photoUrl = photoData;
      }
    },
    searchPhoto() {
      if (this.cameraStream) {
        const canvas = this.$refs.cameraCanvas;
        const video = this.$refs.cameraVideo;
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
        const photoData = canvas.toDataURL('image/jpeg');

        // 调试：检查Base64字符串是否正确
        console.log(photoData);
        this.userInFor.photoData = photoData.split(',')[1];
        this.userInFor.photoData = this.xmUser.id;
        // 将照片数据发送到服务器
        /*
                searchFace({ photoData: photoData.split(',')[1],userId: this.xmUser.id }).then(res => {
        */
        console.log(photoData.split(',')[1])
        console.log(this.xmUser.id)
        searchFace({ photoData: photoData.split(',')[1], userId: this.myInfo.id }).then(res => {

          console.log(res.data.data)
          if (res.data.code === 1) {
            /*const { user_id, score } = res.data.data;*/
            // 显示成功消息，包括用户ID和相似度
            this.$message.success(`照片识别成功` + res.data.data);
            // 如果有其他成功后的操作，可以在这里添加
          } else {
            //this.initVideoPlayer()
            this.$message.error('照片识别失败：' + res.data.msg);
          }
        }).catch(e => {
          this.$message.error('照片识别失败：' + e.message);
        });
        if (this.user_id == 1) {
          this.dialogVisible = false;
          this.closeCamera();
        } else {

        }

        this.photoUrl = photoData;
      }
    },

    getMyInfo() {
      getInfo().then((res) => {
        if (res.data.code === 1) {
          this.myInfo = res.data.data;
          console.log(this.myInfo)
        }
      }).catch((e) => {
      })
    },

    //考试试题列表
    getTestQuestionsListForTest() {
      selectedQuestionAndScore(this.trainingPlanId).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          let code = 1; // 初始化code从1开始
          this.testQuestionList = res.data.data.map(question => {
            // 添加code属性到每个question对象
            return {
              ...question, // 展开原有的question属性
              code: code++ // 添加新的code属性，并且每次调用时递增
            };
          });
          this.ans = this.testQuestionList.reduce((acc, question) => {
            // 对于单选题和判断题，默认答案可以是一个空字符串
            // 对于多选题，默认答案应该是一个空数组
            acc[question.id] = question.type === '多选' ? [] : '';
            return acc;
          }, {});

          if (this.testQuestionList.length !== 0) {
            this.testVisible = true;
          }

        } else {
          this.testVisible = false;
          this.myScore = res.data.msg;
          this.myScoreVisible = true;
        }
      }).catch((e) => {
      })
    },
    handleChange(question) {
      this.$set(this.click, question.id, true);
      console.log(question)
    },

    validateAnswers() {
      this.$confirm("是否交卷", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let score = 0;
        let allSocre = 0;
        this.testQuestionList.forEach(question => {
          if (question.type === '单选' || question.type === '判断') {
            if (this.ans[question.id] === question.ans) {
              score += question.score;
            }
            allSocre += question.score;
          } else if (question.type === '多选') {
            let flag = true;
            // 多选题需要确保所有选项都被选中
            for (let i = 0; i < this.ans[question.id].length; i++) {
              if (!question.ans.includes(this.ans[question.id][i])) {
                flag = false;
              }
            }
            if (flag && this.ans[question.id].length === question.ans.length) {
              score += question.score;
            }
            allSocre += question.score;
          }
        });
        //alert(`你的得分是：${score}/${allSocre}`);
        addScore(this.trainingPlanId, score + "/" + allSocre).then((res) => {
          if (res.data.code === 1) {
            this.$message.success("交卷成功");
            this.testVisible = false;
            this.getTestQuestionsListForTest();
          }
        }).catch((e) => {
        })

      }).catch(() => {

      });
    },
    //点击移动
    scrollToCard(cardId) {
      // 使用ref属性来获取Vue组件实例
      const cardRef = `card-${cardId}`;
      const cardElement = this.$refs[cardRef] && this.$refs[cardRef][0]?.$el; // 获取卡片元素的 DOM 节点

      //console.log("cardElement", cardElement);

      if (cardElement) {
        // 使用scrollIntoView方法滚动到卡片位置
        cardElement.scrollIntoView({
          behavior: 'smooth', // 平滑滚动
          block: 'start', // 滚动到卡片顶部
          inline: 'nearest' // 滚动到卡片最近的边缘
        });
      }
    }


  },

  mounted() {
    this.show();
    this.getAllAgencyList();
    this.getMyInfo()
    // this.cameraVisible = true;
    // this.initCamera();

  },
};
</script>


<style>
* {
  margin: 0;
  padding: 0;
}

.el-header {
  background-color: rgb(238, 241, 246);
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: white;
}
</style>
<script setup>
</script>
